package com.asman.worker.rn

import android.app.Activity
import android.content.Intent
import android.util.Log
import androidx.fragment.app.FragmentActivity
import com.facebook.react.bridge.*
import com.facebook.react.module.annotations.ReactModule
import com.jph.takephoto.model.TResult
import com.utils.PhotoBottomSheet
import com.utils.TakePhotoCallBack
import java.util.*

/**
 * author : ybk
 * date   : 2019-07-18 19:47
 * desc   :
 */
@ReactModule(name = "NativeTakePhoto")
class NativeTakePhoto(reactContext: ReactApplicationContext) :
    ReactContextBaseJavaModule(reactContext) {

    var photoBottomSheet: PhotoBottomSheet? = null

    private val mActivityEventListener = object : BaseActivityEventListener() {
        override fun onActivityResult(
            activity: Activity?, requestCode: Int, resultCode: Int, intent: Intent?
        ) {
            photoBottomSheet?.onActivityResult(requestCode, resultCode, intent)
        }
    }

    init {
        reactContext.addActivityEventListener(mActivityEventListener)
    }

    override fun getName(): String {
        return "NativeTakePhoto"
    }

    override fun getConstants(): Map<String, Any>? {
        val constants = HashMap<String, Any>()
        return constants
    }

    /**
     * 拍照&选择相册 弹出dialog
     * @param count 最大数
     * @param type 1：照片，2：照片+视频，
     * @param promise Promise
     * @return 字符串数组["","",""]
     */
    @ReactMethod
    fun show(count: Int, type: Int, promise: Promise) {
        photoBottomSheet = PhotoBottomSheet.get()
        photoBottomSheet!!.show(
            (currentActivity as FragmentActivity).supportFragmentManager,
            count,
            type == 2,
            object : TakePhotoCallBack.OnChoosePhoneResult {
                override fun onHandlerSuccess(result: TResult) {
                    if (result.images.isNotEmpty()) {
                        val paths = WritableNativeArray()
                        result.images.forEach {
                            Log.d("--------", it.originalPath)
                            paths.pushString("file://" + it.originalPath)
//                            paths.pushString(it.originalPath)
                        }
                        promise.resolve(paths)
                    } else {
                        promise.reject("error", "获取图片失败")
                    }
                }

                override fun onHandlerFailure(errorMsg: String) {
                    promise.reject("error", errorMsg)
                }
            })
    }

}



